package com.sdy.kzyy.web.controller;

import com.sdy.common.model.BizException;
import com.sdy.common.model.Response;
import com.sdy.common.utils.Assert;
import com.sdy.kzyy.biz.model.User;
import com.sdy.kzyy.biz.service.UserService;
import com.sdy.kzyy.web.config.WxConfig;
import com.sdy.kzyy.web.config.WxSession;
import com.sdy.mvc.controller.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * <p>
 * 注释
 * </p>
 *
 * @author fb
 * @since 2020/3/4
 */
@RestController
@RequestMapping("/login")
@Api(tags = "登录接口")
public class LoginController extends BaseController {

    @Value("${res.app.bindphone}")
    private Boolean bindphone;
    @Value("${res.app.env.test:true}")
    private Boolean envTest;
    @Autowired
    private UserService userService;

    /**
     * 微信登录
     * @param code 微信code
     */
    @PostMapping("/wxOaLogin")
    @ApiOperation(value = "微信公众号登录")
    @ApiImplicitParam(value = "微信公众号code", name = "code", required = true)
    public Response wxOaLogin(String code, HttpServletRequest request) throws BizException {
        Assert.isBlank(code, "微信code不能为空");
        WxSession wxSession = decryptWxIdByOa(code);
        Assert.isNull(wxSession, "微信会话解析失败。");
        User user;
        if (bindphone) {
            // 需要绑定手机号
            user = userService.getUserByWxid(wxSession.getWxId());
            if (user == null) {
                return Response.error("未绑定微信，请先使用手机号登录", -999);
            }
        } else {
            user = userService.xGetOrCreateUserByWxid(wxSession.getWxId());
        }
        request.getSession().setAttribute(com.sdy.common.constant.Constants.SESSION_USER_ID, user.getId());
        return Response.success();
    }

    @GetMapping("/logout")
    @ApiOperation(value = "登出")
    public Response logout(HttpServletRequest request) {
        request.getSession().removeAttribute(com.sdy.common.constant.Constants.SESSION_USER_ID);
        return Response.success();
    }

    @GetMapping("/loginTest")
    @ApiOperation(value = "测试登录")
    public Response loginTest(HttpServletRequest request, Integer userId) {
        if (!envTest) {
            return Response.error("请在测试环境使用。");
        }
        User user = null;
        if(userId != null) {
            user = userService.getById(userId);
        }
        if(user != null) {
            request.getSession().setAttribute(com.sdy.common.constant.Constants.SESSION_USER_ID, user.getId());
        }else {
            return Response.error("用户不存在。");
        }
        return Response.success("测试登录成功。");
    }

    private WxSession decryptWxIdByOa(String code) {
        WxSession wxSession = new WxSession();
        Map<String, Object> resp = WxConfig.oaCodeToSession(code);
        wxSession.setOpenId((String) resp.get("openid"));
        wxSession.setUnionId((String) resp.get("unionid"));
        wxSession.setSessionKey((String) resp.get("access_token"));
        return wxSession;
    }

}
